package com.cskaoyan.market.controller.Admin;

import com.cskaoyan.market.annotation.RequiresPermissionsDesc;
import com.cskaoyan.market.db.domain.MarketComment;
import com.cskaoyan.market.service.admin.MarketCommentService;
import com.cskaoyan.market.util.ResponseUtil;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("/admin/comment")
public class AdminCommentController extends HttpServlet {
    @Autowired
    private MarketCommentService marketCommentService;

    @Autowired
    private ObjectMapper objectMapper;


    @RequiresPermissions("admin:comment:delete")
    @RequiresPermissionsDesc(menu = {"商品管理", "评论管理"}, button = "删除")
    @PostMapping("delete")
    public Object delete(HttpServletRequest req) throws IOException {
        BufferedReader requestBody = req.getReader();
        MarketComment marketComment = objectMapper.readValue(requestBody, MarketComment.class);
        marketCommentService.delete(marketComment);
        return ResponseUtil.ok();
    }

    @RequiresPermissions("admin:comment:list")
    @RequiresPermissionsDesc(menu = {"商品管理", "评论管理"}, button = "查询")
    @GetMapping("list")
    public Object list(HttpServletRequest req) {
        String pageParam = req.getParameter("page");
        String limitParam = req.getParameter("limit");
        String userId = req.getParameter("userId");
        String valueId = req.getParameter("valueId");
        String sort = req.getParameter("sort");
        String order = req.getParameter("order");
        Integer page = null;
        Integer limit = null;
        //如果输入的页码和条数参数不是数字
        try {
            page = Integer.parseInt(pageParam);
            limit = Integer.parseInt(limitParam);
        } catch (Exception e) {
            //输出参数错误
            //将json文本转换为字符串
            return ResponseUtil.badArgument();
        }
        //处理业务逻辑
        List<MarketComment> marketCommentList = marketCommentService.list(page, limit, userId, valueId, sort, order);
        //返回响应
        return ResponseUtil.okList(marketCommentList);
    }
}

